<template>
	<div class="container">
		<el-form class="form" label-width="120px" label-position="top">
			<el-form-item label="年: ">
				<el-col :span="16">
					<el-input type="number" v-model="year" />
				</el-col>
			</el-form-item>
			<el-form-item label="月: ">
				<el-col :span="16">
					<el-input type="number" v-model="day" />
				</el-col>
			</el-form-item>
			<el-form-item label="请导入文件: ">
				<el-col :span="16">
					<div style="text-align: left">
						<input type="file" ref="file" />
					</div>
				</el-col>
			</el-form-item>
			<el-button type="primary" @click="plImport">确定</el-button>
		</el-form>
	</div>
</template>

<script>
import { ElMessage } from "element-plus";
import { read, utils } from "xlsx";
export default {
	name: "ImportStudentScore",
	data() {
		return {
			output: [],
			year: "",
			day: "",
		};
	},
	methods: {
		readExcel(e) {
			const files = e.target.files;
			// 如果没有文件名
			if (files.length <= 0) {
				return false;
			} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
				alert("上传格式不正确，请上传xls或者xlsx格式");
				return false;
			}

			const fileReader = new FileReader();
			fileReader.onload = (ev) => {
				try {
					const data = ev.target.result;
					// 切换为新的调用方式
					const workbook = read(data, {
						type: "binary",
					});
					this.output = [];
					for (let name of workbook.SheetNames) {
						this.output[name] = utils.sheet_to_json(workbook.Sheets[name]);
					}
					// console.log(this.output);
				} catch (e) {
					return false;
				}
			};
			fileReader.readAsBinaryString(files[0]);
		},
		plImport() {
			let students = [];
			for (let name in this.output) {
				let item = this.output[name];
				for (let i in item) {
					let student = {
						times: "" + this.year + this.day,
					};
					let wt = item[i];
					let keys = Object.keys(wt);
					keys.forEach((key) => {
						if (/学号/.test(key)) {
							student["studentID"] = wt[key];
						} else if (/姓名/.test(key)) {
							student["studentName"] = wt[key];
						} else if (/(成绩|分数)/.test(key)) {
							student["lastScore"] = wt[key];
						}
					});
					students.push(student);
				}
			}
			// console.log(students);
			fetch(`${this.$store.getters.point}/score/saveScore`, {
				method: "POST",
				body: JSON.stringify(students),
				headers: {
					"Content-Type": "application/json",
				},
			})
				.then((response) => response.text())
				.then((result) => {
					let data = parseInt(JSON.parse(result).code);
					if (data == 1) {
						ElMessage({
							message: "导入成功",
							type: "success",
						});
						this.$emit("success");
					} else {
						ElMessage({
							message: "导入失败",
							type: "error",
						});
					}
				});
		},
	},
	mounted() {
		this.$refs.file.addEventListener("change", (e) => {
			this.readExcel(e);
		});
	},
};
</script>

<style scoped></style>
